﻿using System;
using System.Text.RegularExpressions;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Oracle;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Unis.Framework.Core.Exceptions;
using Unis.Framework.ORM.BaseDefiniens.Enums;

namespace Unis.Framework.ORM.Persistence
{
    public class DatabaseConfigurationScope : IDisposable
    {
        // Fields
        [ThreadStatic]
        private static string _OldConfigurationDatabase = ConfigurationDatabase;
        [ThreadStatic]
        public static string ConfigurationDatabase;
        private bool disposed;
        private static string[] MY_SQL_DB_PROVIDER = new string[] { "MySql.Data.MySqlClient.MySqlClientFactory" };

        // Methods
        public DatabaseConfigurationScope(string configurationDatabase)
        {
            ConfigurationDatabase = configurationDatabase;
        }

        public static DatabaseType CreateDatabaseType()
        {
            return GetDatabaseType(DatabaseHelper.CreateDatabase());
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    ConfigurationDatabase = _OldConfigurationDatabase;
                }
                this.disposed = true;
            }
        }

        ~DatabaseConfigurationScope()
        {
            this.Dispose(false);
        }

        public static DatabaseType GetDatabaseType(Database db)
        {
            if (db is OracleDatabase)
            {
                return DatabaseType.Oracle;
            }
            if (db is SqlDatabase)
            {
                return DatabaseType.MSSQLServer;
            }
            if (db is GenericDatabase)
            {
                string str = db.DbProviderFactory.ToString();
                if (Array.IndexOf<string>(MY_SQL_DB_PROVIDER, str) >= 0)
                {
                    return DatabaseType.MySql;
                }
                return DatabaseType.Oracle;
            }
            if (!Regex.IsMatch(db.ConnectionString, ".db3", RegexOptions.IgnoreCase))
            {
                throw new APPException(string.Format("当前数据库类型{0} 目前还不支持,先要实现对应的类", db.ToString()), APPMessageType.SysDatabaseInfo);
            }
            return DatabaseType.Sqlite;
        }
    }
}
